package com.yzy.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.yzy.entity.Teacher;
import com.yzy.service.ITeacherService;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author 杨子宇
 */
@Component
public class TeaTokenUtils {
    private static ITeacherService staticTeacherService;

    @Resource
    private ITeacherService teacherService;

    @PostConstruct
    public void setTeacherService() {
        staticTeacherService = teacherService;
    }

    /**
     * 获取token
     */
    public static String getToken(Teacher teacher) {
        String tid = teacher.getTid().toString();
        String username = teacher.getUsername();

        return JWT.create().withAudience(tid)
                // 设置 24 小时后Token过期
                .withExpiresAt(DateUtil.offsetHour(new Date(), 24))
                // 将教师用户名作为Token秘钥
                .sign(Algorithm.HMAC256(username));
    }

    /**
     * 获取当前登录的教师信息
     */
    public static Teacher getCurrentTeacher() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("Tea-token");
            if (StrUtil.isNotBlank(token)) {
                String teacherId = JWT.decode(token).getAudience().get(0);
                return staticTeacherService.getById(Integer.valueOf(teacherId));
            }
        } catch (Exception e) {
            return null;
        }

        return null;
    }
}
